package com.charlotte.study.gupao.proxy.dbroute.proxy;

import com.charlotte.study.gupao.proxy.dbroute.DynamicDataSourceEntity;
import com.charlotte.study.gupao.proxy.dbroute.IOrderService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author junjie.ding
 * @date 2020/3/3
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");

    private IOrderService target;

    public IOrderService getInstance(IOrderService target){
        this.target = target;
        Class<?> targetClass = target.getClass();
        return (IOrderService) Proxy.newProxyInstance(targetClass.getClassLoader(), targetClass.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(args[0]);
        Object o = method.invoke(this.target, args);
        after();
        return o;
    }


    //target 应该是订单对象Order
    private void before(Object target) {
        try {
            // 进行数据源的切换
            System.out.println("Proxy before method");
            // 约定优于配置
            Long time = (Long) target.getClass().getMethod("getCreateTime").invoke(target);
            Integer dbRouter = Integer.valueOf(yearFormat.format(new Date(time)));
            System.out.println("静态代理类自动分配到【DB_" + dbRouter + "】数据源处理数据");
            DynamicDataSourceEntity.set(dbRouter);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void after() {
        System.out.println("Proxy after method");
        //还原成默认的数据源
        DynamicDataSourceEntity.restore();
    }


}
